package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.entity.User;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShortCarMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import lombok.RequiredArgsConstructor;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    private final AddressBookMapper addressBookMapper;
    @Autowired
    private ShortCarMapper shortCarMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;


    @Autowired
    private OrderDetailMapper orderDetailMapper;


    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1、前置条件判断
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        QueryWrapper<ShoppingCart> wrapper = new QueryWrapper<ShoppingCart>()
                .select("*")
                .ge("userId", BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCarts = shortCarMapper.selectList(wrapper);

//        List<ShoppingCart> shoppingCarts = shortCarMapper.queryByUserId(BaseContext.getCurrentId());
        if (shoppingCarts == null || shoppingCarts.size() <= 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //2、订单表插入数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(1);
        orders.setUserId(BaseContext.getCurrentId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayMethod(1);
        orders.setPayStatus(0);
        orders.setPhone(addressBook.getPhone());
        //详细地址
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        User user = userMapper.queryById(addressBook.getUserId());
        orders.setUserName(user.getOpenid());
        orders.setConsignee(addressBook.getConsignee());
        //送达时间 ，现在时间加一个小时
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime nowPlusOneHour = now.plusHours(1);
        orders.setDeliveryTime(nowPlusOneHour);
        //
        orderMapper.insert(orders);
        List<OrderDetail> orderDetailList = new ArrayList<>();
        shoppingCarts.forEach(item -> {
            OrderDetail orderDetail = OrderDetail.builder().orderId(orders.getId()).name(item.getName())
                    .image(item.getImage()).dishId(item.getDishId()).dishFlavor(item.getDishFlavor()).number(item.getNumber()).setmealId(item.getSetmealId())
                    .amount(item.getAmount()).build();
            orderDetailList.add(orderDetail);
        });

        //3、插入订单明细表
        orderDetailMapper.batchInsert(orderDetailList);

        //4、清空购物车
        shortCarMapper.deleteByUserId(BaseContext.getCurrentId());

        //5、返回订单数据
//        OrderVO.builder().id(orders.getId()).number(orders.getNumber()).orderTime(orders.getOrderTime()).
//        Or
        return OrderSubmitVO.builder().id(orders.getId())
                .orderTime(orders.getOrderTime()).orderAmount(orders.getAmount()).orderNumber(orders.getNumber()).build();

    }

    @Override
    public PageResult pageQuer(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuer(ordersPageQueryDTO);
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;

    }

    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO vo = new OrderStatisticsVO();
        vo.setConfirmed(orderMapper.countByStatus(3));
        vo.setToBeConfirmed(orderMapper.countByStatus(2));
        vo.setDeliveryInProgress(orderMapper.countByStatus(4));
        return vo;
    }

    @Override
    public OrderVO details(Long id) {
        //1、先查询订单信息
        Orders orders = orderMapper.selectById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);

        //2、查询关联的订单详情信息
        List<OrderDetail> orderDetailList = orderDetailMapper.queryByOrderId(id);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersCancelDTO, orders);
        orders.setStatus(6);
        orderMapper.updateById(orders);
    }
}
